package com.example.myspringbootpj.controller;

import com.example.myspringbootpj.entity.User;
import com.example.myspringbootpj.mapper.UserMapper;
import com.example.myspringbootpj.service.addUserService;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@RestController
@RequestMapping("/uploadUser")
public class FileController {

    private static final Logger logger = LoggerFactory.getLogger(FileController.class);

    private static final String FIXED_FILE_PATH = "D:" + File.separator + "fgobb" + File.separator + "uploaded_images";

    private final addUserService addUserService;

    @Autowired
    public FileController(addUserService addUserService) {
        this.addUserService = addUserService;
    }

    @CrossOrigin(origins = "http://localhost:63342")
    @PostMapping(value = "/register", consumes = {"multipart/form-data"})
    public ResponseEntity<String> uploadUser(
            @RequestParam("user_id") String userId,
            @RequestParam("user_password") String userPassword,
            @RequestParam("user_name") String userName,
            @RequestParam(value = "user_image", required = false) MultipartFile userImage) {

        // 检查账号是否重复
        if (addUserService.isUserIdExists(userId)) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                    .body("注册失败，账号已存在");
        }

        // 创建用户对象
        User user = new User();
        user.setUser_id(userId);
        user.setUser_password(userPassword);
        user.setUser_name(userName);

        // 处理文件上传
        if (userImage != null && !userImage.isEmpty()) {
            try {
                String savedFilePath = saveFile(userImage, FIXED_FILE_PATH);
                user.setUser_image(savedFilePath);
            } catch (IOException e) {
                logger.error("文件上传失败: {}", e.getMessage(), e);
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                        .body("注册失败，文件上传失败");
            }
        } else {
            user.setUser_image(null); // 没有图片上传时设置为 null
        }

        // 调用服务注册用户
        boolean success = addUserService.register(user);
        if (!success) {
            logger.error("用户注册失败: 数据库插入失败");
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("注册失败，数据库操作失败");
        }

        return ResponseEntity.ok("注册成功！");
    }

    private String saveFile(MultipartFile userImage, String path) throws IOException {
        if (userImage.isEmpty()) {
            throw new IOException("文件为空");
        }

        File dir = new File(path);
        if (!dir.exists() && !dir.mkdirs()) {
            logger.error("创建目录失败: {}", path);
            throw new IOException("无法创建目录: " + path);
        }

        File file = new File(dir, userImage.getOriginalFilename());
        try {
            userImage.transferTo(file);
            logger.info("文件保存成功: {}", file.getAbsolutePath());
        } catch (IOException e) {
            logger.error("文件保存失败", e);
            throw new IOException("文件保存失败: " + e.getMessage(), e);
        }
        return file.getAbsolutePath();
    }
}


//@RestController
//public class FileController {
//
//    private static final Logger logger = LoggerFactory.getLogger(FileController.class);
//
//    private static final String FIXED_FILE_PATH = "D:" + File.separator + "fgobb" + File.separator + "uploaded_images";
//
//    private addUserService addUserService;
//    private UserMapper userMapper;
//
//    @Autowired
//    public FileController(addUserService addUserService, UserMapper userMapper) {
//        this.addUserService = addUserService;
//        this.userMapper = userMapper;
//    }
//    //用户注册
//    @CrossOrigin(origins = "http://localhost:63342")
//    @RequestMapping(value = "/uploadUser", method = RequestMethod.POST, consumes = {"multipart/form-data"})
//    public String uploadUser(
//            @RequestParam("user_id") String userId,
//            @RequestParam("user_password") String userPassword,
//            @RequestParam("user_name") String userName,
//            @RequestParam("user_image") MultipartFile user_image) throws IOException {
//
//        if (user_image.isEmpty()) {
//            return "上传失败，文件为空";
//        }
//
//
//        // 检查账号是否重复
//        if (addUserService.isUserIdExists(userId)) {
//            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
//                    .body("注册失败，账号已存在");
//        }
//
//
//
//
//
//        // 创建User对象并设置属性
//        User user = new User();
//        user.setUser_id(userId);
//        user.setUser_password(userPassword);
//        user.setUser_name(userName);
//
//        // 保存文件
//        String savedFilePath = saveFile(user_image, FIXED_FILE_PATH);
//        user.setUser_image(savedFilePath);
//
//        // 插入用户数据到数据库
//        try {
//            userMapper.add(user);
//        } catch (Exception e) {
////            logger.error("数据库插入用户数据失败，原因: {}", e.getMessage(), e);
//            return "上传失败";
//        }
//
//        logger.info("文件保存路径: {}", savedFilePath);
//        return "上传成功";
//    }
//
//    public String saveFile(MultipartFile user_image, String path) throws IOException {
//        if (user_image == null || user_image.isEmpty()) {
//            throw new IOException("文件为空");
//        }
//
//        File dir = new File(path);
//
//        if (!dir.exists()) {
//            if (!dir.mkdirs()) {
//                logger.error("创建目录失败: {}", path);
//                throw new IOException("无法创建目录: " + path);
//            }
//        }
//
//        File file = new File(path + File.separator + user_image.getOriginalFilename());
//
//        try {
//            logger.info("准备保存文件: {} 到路径: {}", user_image.getOriginalFilename(), file.getAbsolutePath());
//            user_image.transferTo(file);
//            logger.info("文件保存成功: {}", file.getAbsolutePath());
//
//            if (file.exists()) {
//                logger.info("文件已存在: {}", file.getAbsolutePath());
//            } else {
//                logger.error("文件未找到: {}", file.getAbsolutePath());
//                throw new IOException("文件保存失败");
//            }
//        } catch (IOException e) {
//            logger.error("文件保存失败: {}", file.getAbsolutePath(), e);
//            throw new IOException("文件上传失败", e);
//        }
//
//        return file.getAbsolutePath();
//    }
//}
